package info.batcloud.fanli.api.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qrcode")
public class QrcodeController {

    @GetMapping
    public Object execute(Param param, HttpServletResponse response) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, param.getError() == null ? ErrorCorrectionLevel.M : param.getError());
        hints.put(EncodeHintType.MARGIN, param.getMargin());
        BitMatrix bitMatrix = new MultiFormatWriter().encode(param.getText(),
                BarcodeFormat.QR_CODE, param.getSize(), param.getSize(), hints);// 生成矩阵
        response.setContentType("image/" + param.getFormat());
        MatrixToImageWriter.writeToStream(bitMatrix, param.getFormat(), response.getOutputStream());
        response.flushBuffer();
        return null;
    }

    public static class Param {
        private int size;
        private String text;
        private String format = "gif";

        private ErrorCorrectionLevel error;

        private int margin = 2;

        public int getSize() {
            return size;
        }

        public void setSize(int size) {
            this.size = size;
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getMargin() {
            return margin;
        }

        public void setMargin(int margin) {
            this.margin = margin;
        }

        public ErrorCorrectionLevel getError() {
            return error;
        }

        public void setError(ErrorCorrectionLevel error) {
            this.error = error;
        }

    }
}
